//
//  QREventParser.m
//  QRCodeManager
//
//  Created by Cosmin Stirbu on 4/16/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "QREventParser.h"
#import "CoreDataManager.h"

NSString * const TITLE_REG_EX = @"SUMMARY:.*(\\n)*";
NSString * const LOCATION_REG_EX = @"LOCATION:.*(\\n)*";
NSString * const SUMMARY_REG_EX = @"DESCRIPTION:.*(\\n)*";
NSString * const DTSTART_REG_EX = @"DTSTART:.*(\\n)*";
NSString * const DTEND_REG_EX = @"DTEND:.*(\\n)*";

NSString * const SUMMARY_TAG = @"SUMMARY:";
NSString * const LOCATION_TAG = @"LOCATION:";
NSString * const DESCRIPTION_TAG = @"DESCRIPTION:";
NSString * const DTSTART_TAG = @"DTSTART:";
NSString * const DTEND_TAG = @"DTEND:";

@implementation QREventParser 


- (QREvent *)qrEvent {
    NSManagedObjectContext *context = [CoreDataManager sharedInstance].managedObjectContext;
    _qrEvent = (QREvent *)[NSEntityDescription insertNewObjectForEntityForName:@"QREvent" inManagedObjectContext:context];
    _qrEvent.content = _qrData;
    if ([self parse]) {
        return _qrEvent;
    }
    // We delete it if the parsing was faulty
    [context deleteObject:_qrEvent];
    return nil;
}

- (BOOL)parse {
    // Title
    _qrEvent.title = [self valueForRegEx:TITLE_REG_EX withOffset:[SUMMARY_TAG length] trimLength:0];
    
    // Location
    _qrEvent.location = [self valueForRegEx:LOCATION_REG_EX withOffset:[LOCATION_TAG length] trimLength:0];
    
    // Summary
    _qrEvent.summary = [self valueForRegEx:SUMMARY_REG_EX withOffset:[DESCRIPTION_TAG length] trimLength:0];
    
    // Dates and times
    NSString *dateStart = [self valueForRegEx:DTSTART_REG_EX withOffset:[DTSTART_TAG length] trimLength:0];
    NSString *dateEnd = [self valueForRegEx:DTEND_REG_EX withOffset:[DTEND_TAG length] trimLength:0];
    
    if (dateStart == nil || dateEnd == nil)
        return NO;
    
    NSDateFormatter *dateFormatter = [NSDateFormatter new];
    [dateFormatter setDateFormat:@"yyyyMMdd'T'HHmmss'Z'"];
    
    _qrEvent.startdate = [dateFormatter dateFromString:dateStart];
    _qrEvent.enddate = [dateFormatter dateFromString:dateEnd];
    

    return _qrEvent.title != nil && _qrEvent.startdate != nil && _qrEvent.enddate != nil;
}



@end
